//
//  WeightsHistoryViewController.m
//  WeightMaster
//
//  Created by sungeo on 15/8/20.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "WeightsChartController.h"
#import "WMModels.h"
#import "WeightRecordCell.h"
#import "BDFoundation.h"
#import <RandomSequence.h>
#import <DateTools.h>
#import <Masonry.h>
#import <objc/runtime.h>
#import <NSObject+GLPubSub.h>
#import <EXTScope.h>

static NSString * const sIdentifier = @"WeightRecordCell";


@interface WeightsChartController (){    
    UIImageView * _header;
    UIImageView * _footer;
    
    NSInteger _selectedItemIndex;
    NSMutableDictionary * _itemPhotoMap;
}

@end


@implementation WeightsChartController

- (instancetype)init{
    if (self = [super init]) {
        _shouldShowSelectionState = NO;
        _shouldShowDates = NO;
        _selectedItemIndex = -1;
        
        _containerView = [[UIView alloc] init];
        
        const float HeaderHeight = 2;
        UIImage * image = [UIImage imageNamed:@"h_line"];
        
        // 顶部分隔区
        _header = [[UIImageView alloc] initWithImage:image];
        _header.contentMode = UIViewContentModeCenter;
        [_containerView addSubview:_header];
        [_header mas_makeConstraints:^(MASConstraintMaker * maker){
            maker.leading.equalTo(_containerView.mas_left);
            maker.trailing.equalTo(_containerView.mas_right);
            maker.top.equalTo(_containerView.mas_top);
            maker.height.equalTo(@(HeaderHeight));
        }];
        
        
        // 底部分隔区
        _footer = [[UIImageView alloc] initWithImage:image];
        _footer.contentMode = UIViewContentModeCenter;
        [_containerView addSubview:_footer];
        [_footer mas_makeConstraints:^(MASConstraintMaker * maker){
            maker.leading.equalTo(_containerView.mas_left);
            maker.trailing.equalTo(_containerView.mas_right);
            maker.bottom.equalTo(_containerView.mas_bottom);
            maker.height.equalTo(@(HeaderHeight));
        }];

        
        // 中间图表区：设置滚动方向为水平
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_containerView addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker * maker){
            maker.leading.equalTo(_containerView.mas_left);
            maker.trailing.equalTo(_containerView.mas_right);
            maker.top.equalTo(_header.mas_bottom).offset(10);
            maker.bottom.equalTo(_footer.mas_top).offset(-10);
        }];
    
        [_collectionView registerClass:[WeightRecordCell class] forCellWithReuseIdentifier:sIdentifier];
        
        [self registerNotificationHandler];
    }
    
    return self;
}

- (void)registerNotificationHandler{
    @weakify(self);
    
    [self subscribe:PhotoDownloadedNote handler:^(GLEvent * event){
        @strongify(self);
        
        NSString * uuid = event.data;
        if (uuid.length == 0) {
            return;
        }

        WMWeight * weight = [self->_itemPhotoMap objectForKey:uuid];
        if (weight == nil) {
            return;
        }
        
        NSInteger index = [self.items indexOfObject:weight];
        if (NSNotFound == index) {
            return;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
            NSLog(@"更新图标图片，位置：%@", @(index));
        });
    }];
}

- (void)didTouchedCollectionView:(id)sender{
    if (_delegate && [_delegate respondsToSelector:@selector(didTouchedWeightsChartController:withWeight:)]) {
        [_delegate performSelector:@selector(didTouchedWeightsChartController:withWeight:) withObject:_collectionView withObject:nil];
    }
}

- (void)setItems:(NSArray *)items{
    _items = items;
    
    // 计算最大和最小体重
    NSArray * ranges = [[WMDataCache sharedInstance] minAndMaxWeightObjects:_items];
    if (ranges != nil) {
        WMWeight * weight = ranges[0];
        _range.low = [weight.value floatValue];
        weight = ranges[1];
        _range.high = [weight.value floatValue];
    }
    
    // 创建图片 UUID 到体重对象的映射表，用于图片下载成功时更新界面
    _itemPhotoMap = [NSMutableDictionary dictionary];
    for (WMWeight * weight in _items) {
        if (weight.profileUUID.length != 0) {
            [_itemPhotoMap setObject:weight forKey:weight.profileUUID];
        }
    }
}

- (void)moveToRightestItem{
    // 移动到最右一个 item
    // TODO: 先动画，再移动过去，效果不佳
    if (_items && _items.count > 0) {
        NSIndexPath * indexPath = [NSIndexPath indexPathForItem:_items.count - 1 inSection:0];
        [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
        
        NSLog(@"体重图表移动到最右：%@", @(_items.count - 1));
    }
}

- (void)cellProfileClicked:(WeightRecordCell *)cell{
    NSIndexPath * indexPath = [_collectionView indexPathForCell:cell];
    
    [self selectCell:cell atIndex:indexPath.row];
    
    if (_delegate && [_delegate respondsToSelector:@selector(weightsChartController:didTouchedImageAtWeightItem:)]) {
        [_delegate performSelector:@selector(weightsChartController:didTouchedImageAtWeightItem:) withObject:self withObject:cell.weight];
    }
}

/**
 *  对于没有照片的日子，根据体重推理应该展示哪张表情图
 *
 *  @param weight    当前体重对象
 *  @param indexPath 当前体重对象在图表中的位置
 *
 *  @return UIImage 对象
 */
- (UIImage *)moodImageForWeight:(WMWeight *)weight atIndexPath:(NSIndexPath *)indexPath{
    
    WMMood mood = [self moodForWeight:weight atIndexPath:indexPath];
    switch (mood) {
        case WMMoodHappy:
            return [UIImage imageNamed:@"mood_happy"];
        case WMMoodCry:
            return [UIImage imageNamed:@"mood_cry"];
        case WMMoodUnhappy:
            return [UIImage imageNamed:@"mood_unhappy"];
    }
}

- (WMMood)moodForWeight:(WMWeight *)weight atIndexPath:(NSIndexPath *)indexPath{
    float currentValue = [weight.value floatValue];
    NSInteger currentPos = indexPath.row;
    
    if (currentPos == 0 || _items.count == 1) {
        return WMMoodHappy;
    }else{
        float previousValue = [((WMWeight *)_items[currentPos - 1]).value floatValue];
        float difference = currentValue - previousValue;
        if (difference < 0) {
            return WMMoodHappy;
        }else if(difference >= 0 || difference <= 0.5){
            return WMMoodUnhappy;
        }else{
            return WMMoodCry;
        }
    }
}

- (NSInteger)indexOfItemForWeight:(WMWeight *)weight{
    return [_items indexOfObject:weight];
}

- (void)selectCell:(WeightRecordCell *)cell atIndex:(NSInteger)index{
    if (! _shouldShowSelectionState) {
        return;
    }
    
    [cell changeSelectedState:YES];
    
    if (_selectedItemIndex != -1 && index != _selectedItemIndex){
        // 如果上个选中的 cell 可视（is visible），找出来并取消选中状态；否则只能等再次显示的时候再取消
        WeightRecordCell * lastSelectedCell = (WeightRecordCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:_selectedItemIndex inSection:0]];
        if (lastSelectedCell) {
            [lastSelectedCell changeSelectedState:NO];
        }
    }
    
    _selectedItemIndex = index;
}


#pragma mark - UI Collection View data source

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    WeightRecordCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:sIdentifier
                                                                        forIndexPath:indexPath];
    
    [cell addProfileImageClickedListener:self action:@selector(cellProfileClicked:)];
    
    WMWeight * weight = _items[indexPath.row];
    float value = [weight.value floatValue];
    float ratio;
    if (_range.high != _range.low) {
        ratio = (value - _range.low) / (_range.high - _range.low);
    }else{
        ratio = .75f;  // 如果总共只有一个体重对象时显示高度百分比
    }
    
    if (cell == nil) {
        cell = [[WeightRecordCell alloc] initWithWeight:weight ratio:ratio];
    }else{
        cell.weight = weight;
        cell.ratio = ratio;
    }
    
    if ([weight profileImage] == nil) {
        cell.moodImage = [self moodImageForWeight:weight atIndexPath:indexPath];
    }
    
    cell.shouldShowDate = _shouldShowDates;
    
    [cell refreshWithSelectedState:indexPath.row == _selectedItemIndex];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    // 选中某个 Cell
    WeightRecordCell * cell = (WeightRecordCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [self selectCell:cell atIndex:indexPath.row];
    
    if (_delegate && [_delegate respondsToSelector:@selector(didTouchedWeightsChartController: withWeight:)]) {
        WMWeight * weight = _items[indexPath.row];
        [_delegate performSelector:@selector(didTouchedWeightsChartController:withWeight:) withObject:self withObject:weight];
    }
}


#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat width = 0.;
    const CGFloat TotalWidth = self.containerView.frame.size.width;
    const NSInteger MaxItemsShownInScreen = 7;
    const NSInteger count = _items.count;
    if (count != 0) {
        if (count < MaxItemsShownInScreen) {
            width = TotalWidth / count;
        }else{
            width = TotalWidth / MaxItemsShownInScreen;
        }
    }
    
    return CGSizeMake(width, _collectionView.frame.size.height);
}

- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}


@end
